/*
 * 蓝牙权限及开关校验
 * @Author: mosowe
 * @Date:2023-08-25 09:26:43
 */

// 【安卓端】获取所有有关权限，没有授权则跳转设置页面
let hasModal = false;
const androidCheckPermission = () => {
  return new Promise<boolean>((resolve) => {
    if (hasModal) {
      resolve(false);
      return;
    }
    const permissions: any = {
      'android.permission.BLUETOOTH': '蓝牙权限', // 蓝牙权限
      'android.permission.BLUETOOTH_SCAN': '蓝牙权限', // 蓝牙权限
      'android.permission.BLUETOOTH_ADMIN': '蓝牙权限', // 蓝牙权限
      'android.permission.BLUETOOTH_CONNECT': '蓝牙权限', // 蓝牙权限
      'android.permission.ACCESS_FINE_LOCATION': '位置信息权限', // 定位
      'android.permission.ACCESS_COARSE_LOCATION': '位置信息权限' // 定位
    };
    plus.android.requestPermissions(
      Object.keys(permissions), //这里面放需要的权限,我这边主要是打电话以及通讯录的一些操作权限
      function (resultObj) {
        if (resultObj.granted.length < Object.keys(permissions).length) {
          //resultObj.granted是授权的权限，是一个数组，你可以直接判断长度也可以拿出来单独判断
          //resultObj.deniedAlways是拒绝的权限，是一个数组，你可以直接判断长度也可以拿出来单独判断
          let noAuth: any = '';
          resultObj.deniedAlways.forEach((key: string) => {
            noAuth += (noAuth ? ',' : '') + permissions[key];
          });
          console.log('hasModal', hasModal);
          if (!hasModal) {
            hasModal = true;
            uni.showModal({
              content: '程序运行需获取以下权限：' + noAuth,
              showCancel: false,
              success() {
                //没有开对应的权限，打开app的系统权限管理页
                let Intent = plus.android.importClass('android.content.Intent');
                let Settings = plus.android.importClass(
                  'android.provider.Settings'
                );
                let Uri = plus.android.importClass('android.net.Uri');
                let mainActivity = plus.android.runtimeMainActivity();
                let intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                let uri = Uri.fromParts(
                  'package',
                  mainActivity.getPackageName(),
                  null
                );
                intent.setData(uri);
                mainActivity.startActivity(intent);

                hasModal = false;
              }
            });
          }
          resolve(false);
        } else {
          resolve(true);
        }
      }
    );
  });
};

// 【安卓端】启动-蓝牙开关监测-打开-需先授权，没有授权前调用不了
const androidCheckBluetoothSwitch = () => {
  return new Promise<boolean>((resolve) => {
    let main = plus.android.runtimeMainActivity();
    let BluetoothAdapter = plus.android.importClass(
      'android.bluetooth.BluetoothAdapter'
    );
    let BAdapter = new BluetoothAdapter.getDefaultAdapter();
    let receiver = plus.android.implements(
      'io.dcloud.android.content.BroadcastReceiver',
      {
        onReceive: function (context, intent) {
          //实现onReceiver回调函数
          resolve(true);
          plus.android.importClass(intent);
          main.unregisterReceiver(receiver);
        }
      }
    );
    let IntentFilter = plus.android.importClass('android.content.IntentFilter');
    let filter = new IntentFilter();
    filter.addAction(BAdapter.ACTION_STATE_CHANGED); //监听蓝牙开关
    main.registerReceiver(receiver, filter); //注册监听
    if (!BAdapter.isEnabled()) {
      BAdapter.enable(); //启动蓝牙
    }
  });
};

// 【ios端】，获取蓝牙适配器状态
const iosCheckBluetoothStatus = () => {
  return new Promise<boolean>((resolve, reject) => {
    const notice: any = {
      10000: '程序运行需获取蓝牙权限',
      10001: '蓝牙未开启'
    };
    plus.bluetooth.getBluetoothAdapterState({
      success: (res: any) => {
        resolve(true);
      },
      fail: (res: any) => {
        uni.showModal({
          content: notice[res.code],
          showCancel: false,
          confirmText: '前往设置',
          success() {
            // 打开应用权限设置页面
            let UIApplication = plus.ios.import('UIApplication');
            let application2 = UIApplication.sharedApplication();
            let NSURL2 = plus.ios.import('NSURL');
            let setting2 = NSURL2.URLWithString('app-settings:');

            if (res.code === 10000) {
              setting2 = NSURL2.URLWithString('app-settings:');
            }
            if (res.code === 10001) {
              setting2 = NSURL2.URLWithString('App-Prefs:');
            }

            application2.openURL(setting2);
            plus.ios.deleteObject(setting2);
            plus.ios.deleteObject(NSURL2);
            plus.ios.deleteObject(application2);
          }
        });
        resolve(false);
      }
    });
  });
};

// 蓝牙校验：权限及开关
export default () => {
  return new Promise<boolean>((resolve) => {
    const platform = uni.getSystemInfoSync().platform;
    if (platform === 'android') {
      androidCheckPermission().then((bool: boolean) => {
        androidCheckBluetoothSwitch();
        if (bool) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    } else {
      iosCheckBluetoothStatus().then((bool: boolean) => {
        if (bool) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    }
  });
};
